#include "MQTT_Driver.h"
#include "portmacro.h"
#include "esp_log.h"

static const char *TAG = "MQTT_EXAMPLE";

// MQTT事件处理函数
static void mqtt_event_handler(void *args, esp_event_base_t base,
                               int32_t event_id, void *event_data)
{
    esp_mqtt_event_handle_t event = event_data;
    switch (event->event_id)
    {

    case MQTT_EVENT_CONNECTED:
    {
        static bool is_subscribed = false;
        if (!is_subscribed)
        {
            ESP_LOGI(TAG, "首次订阅主题");
            esp_mqtt_client_subscribe(event->client, "sys/oyhju8e3h8/n8l85e60993pphp/property/set", 0);
            is_subscribed = true;
        }
        else
        {
            ESP_LOGW(TAG, "检测到重连，自动维持订阅状态");
        }
        break;
    }

    case MQTT_EVENT_DATA: // 消息接收处理
        ESP_LOGI(TAG, "Received %d bytes data", event->data_len);

        // 解析JSON消息
        cJSON *root = cJSON_Parse(event->data);
        if (root)
        {
            cJSON *params = cJSON_GetObjectItem(root, "params");
            if (params)
            {
                cJSON *ota_cmd = cJSON_GetObjectItem(params, "ota_command");
                cJSON *fw_url = cJSON_GetObjectItem(params, "fw_url");

                if (cJSON_IsString(ota_cmd) && (strcmp(ota_cmd->valuestring, "start") == 0))
                {
                    ota_trigger_flag = 1; // 设置OTA触发标志
                    if (cJSON_IsString(fw_url))
                    {
                        strncpy(ota_fw_url, fw_url->valuestring, sizeof(ota_fw_url) - 1);
                    }
                    ESP_LOGI(TAG, "OTA Triggered, URL: %s", ota_fw_url);
                }
            }
            cJSON_Delete(root);
        }
        break;

    case MQTT_EVENT_DISCONNECTED:
        ESP_LOGE(TAG, "MQTT Connection Lost");
        break;

    default:
        break;
    }
}

//  MQTT启动函数
static void mqtt_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
        .broker.address.uri = "mqtt://192.168.0.101",
        .credentials.client_id = "n8l85e60993pphp", // 设备ID
        .credentials.username = "r47feu3x",         // 用户名，在mqtt上的设备名称
        .credentials.authentication.password = "111111",
    };

    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */

    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    
    esp_mqtt_client_start(client);

    vTaskDelay(5000 / portTICK_PERIOD_MS);

    
    esp_mqtt_client_subscribe(client, "sys/oyhju8e3h8/n8l85e60993pphp/property/set", 0);// 订阅主题 ，最后的0是qos

    

    // vTaskDelay(5000 / portTICK_PERIOD_MS);
    // 发布消息
    // esp_mqtt_client_publish(client, "sys/oyhju8e3h8/n8l85e60993pphp/property/set", "{\"id\":\"zuoyuan\",\"params\":{\"Clarity\":\"1\"}}", 0, 0, 0);
}


// MQTT初始化函数
void MQTT_Init(void)
{
    ESP_LOGI(TAG, "[APP] Startup..");
    ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size());
    ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());

    esp_log_level_set("*", ESP_LOG_INFO);
    esp_log_level_set("mqtt_client", ESP_LOG_VERBOSE);
    esp_log_level_set("MQTT_EXAMPLE", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_BASE", ESP_LOG_VERBOSE);
    esp_log_level_set("esp-tls", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
    esp_log_level_set("outbox", ESP_LOG_VERBOSE);

    printf("mqtt开始\n");
    mqtt_app_start();
}